package com.longxi.tianjintianbao.ui.presenter.main;

import android.content.Intent;
import android.net.Uri;

import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.listener.SearchListener;
import com.longxi.tianjintianbao.listener.SelectContactDetailListener;
import com.longxi.tianjintianbao.model.Search;
import com.longxi.tianjintianbao.model.contact.ContactDepartment;
import com.longxi.tianjintianbao.model.contact.ContactDetail;
import com.longxi.tianjintianbao.ui.activity.contact.ContactSearchActivity;
import com.longxi.tianjintianbao.ui.adapter.multitype.SearchViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.contact.ContactDeptnamentViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.base.LazyFragment;
import com.longxi.tianjintianbao.ui.presenter.contact.ContactSearchAtPresenter;
import com.longxi.tianjintianbao.ui.view.main.IContactFgView;
import com.longxi.tianjintianbao.utils.MyUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ContactFgPresenter extends BasePresenter<IContactFgView> {

    private MultiTypeAdapter adapter;
    private Items items;
    List<ContactDetail> contactDetailList = new ArrayList<>();

    public ContactFgPresenter(BaseActivity context, LazyFragment fragment) {
        super(context, fragment);
    }

    public void setBar() {
        mFragment.setTitle("联系人");
        mFragment.setTvRight("添加");
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            adapter.register(Search.class, new SearchViewBinder(searchListener));
            adapter.register(ContactDepartment.class, new ContactDeptnamentViewBinder(selectContactDetailListener));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    public void getContactsList(){
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().getContactsList(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<ContactDepartment>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mFragment.showError();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<ContactDepartment> result) {
                if(result.getData().size() == 0){
                    mFragment.showNoData();
                    return;
                }
                contactDetailList = new ArrayList<>();
                items = new Items();
                items.add(new Search("找人"));
                for (ContactDepartment contactDepartment : result.getData()) {
                    contactDepartment.setOpen(false);
                    if(contactDepartment.getDetailed().size() != 0){
                        items.add(contactDepartment);
//                        items.addAll(contactDepartment.getDetailed());
                        contactDetailList.addAll(contactDepartment.getDetailed());
                    }
                }
                adapter.setItems(items);
                adapter.notifyDataSetChanged();
                mFragment.hideLoading();
            }
        });
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public void diallPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        mContext.startActivity(intent);
    }



    SearchListener searchListener = new SearchListener() {
        @Override
        public void onSearch(String keyword) {
            Intent intent = new Intent(mContext, ContactSearchActivity.class);
            intent.putExtra(ContactSearchAtPresenter.CONTACTDETAILLIST, (Serializable) contactDetailList);
            mContext.startActivity(intent);
        }
    };

    SelectContactDetailListener selectContactDetailListener = new SelectContactDetailListener() {
        @Override
        public void onSuccess(ContactDetail contactDetail) {
            diallPhone(contactDetail.getPersonnelphone());
        }
    };

    public void onDestroy() {
        searchListener = null;
        selectContactDetailListener = null;
    }
}
